<template>
  <div>
    <!--  面包屑  -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  卡片  -->
    <el-card>
      <el-row :gutter="20">
        <!--    添加角色区域    -->
        <el-col :span="4">
          <el-button @click="setAddRoles" type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!--   角色列表区域   -->
      <el-table
        border
        stripe
        :data="rolelist"
        style="width: 100%">
        <!--    展开列    -->
        <el-table-column
          type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
                    v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <!--  渲染一级权限  -->
              <el-col :span="5">
                <el-tag
                  @close="removeRightById(scope.row,item1.id)"
                  closable>{{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--  渲染二级三级权限  -->
              <el-col :span="19">
                <!--       通过for 循环 嵌套渲染二级权限         -->
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                        v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag
                      @close="removeRightById(scope.row,item2.id)"
                      closable
                      type="success">{{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag @close="removeRightById(scope.row,item3.id)"
                            closable
                            v-for="(item3) in item2.children"
                            :key="item3.id"
                            type="warning">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!--    索引列    -->
        <el-table-column
          align="center"
          type="index">
        </el-table-column>
        <el-table-column
          prop="roleName"
          align="center"
          label="角色名称">
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          align="center"
          label="角色描述">
        </el-table-column>
        <el-table-column
          align="center"
          width="200px"
          label="操作">
          <template slot-scope="scope">
            <span style="display: none">{{scope.row}}</span>
            <!--      修改      -->
            <el-button type="primary"
                       @click="setUpdateRoles(scope.row.id)"
                       icon="el-icon-edit"
                       size="small"></el-button>
            <!--     分配权限       -->
            <el-tooltip :enterable="false"
                        effect="dark"
                        content="分配权限"
                        placement="top-start">
              <el-button @click="showSetRightDialog(scope.row)"
                         type="warning"
                         icon="el-icon-setting"
                         size="small"></el-button>
            </el-tooltip>
            <!--      删除      -->
            <el-button type="danger"
                       @click="delUserRoles(scope.row.id)"
                       icon="el-icon-delete"
                       size="small"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--  展示权限分配对话框  -->
    <el-dialog
      title="权限分配"
      @close="SetRightDialogClosed"
      :visible.sync="SetRightDialogVisible"
      width="50%">
      <!--   主体区域   -->
      <el-tree
        ref="treeRef"
        :default-expand-all="true"
        node-key="id"
        :default-checked-keys="defKeys"
        show-checkbox
        :data="rightslist"
        :props="treeProps">
      </el-tree>
      <!--   按钮区域   -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="allotRigths">确 定</el-button>
      </span>
    </el-dialog>
    <!--  添加角色对话框  -->
    <el-dialog
      title="添加角色"
      :visible.sync="SetAddRightDialogVisible"
      width="50%">
      <!--   主体区域   -->
      <el-form :model="addFromRoles"
               :rules="addFromUserRoles"
               ref="addFromUserRef"
               label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addFromRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addFromRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--   按钮区域   -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetAddRightDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="SetAddRolesData">确 定</el-button>
      </span>
    </el-dialog>
    <!--  修改角色对话框  -->
    <el-dialog
      @close="updateRolesClosed"
      title="修改角色"
      :visible.sync="SetUpdateRightDialogVisible"
      width="50%">
      <!--   主体区域   -->
      <el-form :model="updateFromRoles"
               :rules="addFromUserRoles"
               ref="updateFromUserRef"
               label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="updateFromRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="updateFromRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--   按钮区域   -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetUpdateRightDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="SetUpdateRolesData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>export default {
  name: 'Roles',
  data () {
    return {
      // 角色列表数据
      rolelist: [],
      // 分配权限对话框
      SetRightDialogVisible: false,
      // 所有权限数据
      rightslist: [],
      // 树形控件数据绑定
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点
      defKeys: [],
      // 角色id
      roleId: '',
      // 添加角色
      SetAddRightDialogVisible: false,
      addFromRoles: {
        roleName: '',
        roleDesc: ''
      },
      // 修改角色
      SetUpdateRightDialogVisible: false,
      updateFromRoles: {
        roleName: '',
        roleDesc: ''
      },
      // 校验
      addFromUserRoles: {
        roleName: [
          {
            required: true, message: '请输入角色名', trigger: 'blur'
          },
          {
            min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'
          }
        ]
      }
    }
  },
  mounted () {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    getRolesList () {
      this.$http.get('roles').then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error(res.data.meta.msg)
        }
        this.rolelist = res.data.data
      })
    },
    // 根据id删除tag
    removeRightById (role, rightId) {
      this.$alert('确定删除吗', '删除标签', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        this.$http.delete(`roles/${role.id}/rights/${rightId}`).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error(res.data.meta.msg)
          }
          this.$message.success(res.data.meta.msg)
          // this.getRolesList()
          // 无刷新加载
          role.children = res.data.data
        })
      }).catch(err => err)
    },
    // 展示分配权限对话框
    showSetRightDialog (role) {
      this.roleId = role.id
      this.$http.get('rights/tree').then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error(res.data.meta.msg)
        }
        this.getLeafKeys(role, this.defKeys)
        this.rightslist = res.data.data
        this.SetRightDialogVisible = true
      })
    },
    // 递归函数
    getLeafKeys (node, arr) {
      // 如果当前node节点不包含childen 属性 则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限列表对话框
    SetRightDialogClosed () {
      // 解决id重复问题
      this.defKeys = []
    },
    // 请求分配权限
    allotRigths () {
      // 获取树形控件所有数据
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedNodes()
      ]
      const idStr = keys.join(',')
      this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr }).then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error(res.data.meta.msg)
        }
        this.$message.success(res.data.meta.msg)
        this.SetRightDialogVisible = false
        this.getRolesList()
      })
    },
    // 删除角色
    delUserRoles (id) {
      this.$alert('确定删除吗', '删除角色', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        this.$http.delete('roles/' + id).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error(res.data.meta.msg)
          }
          this.$message.success(res.data.meta.msg)
          this.getRolesList()
        })
      }).catch(err => err)
    },
    // 添加角色
    setAddRoles () {
      this.SetAddRightDialogVisible = true
    },
    // 添加请求
    SetAddRolesData () {
      this.$refs.addFromUserRef.validate(valid => {
        if (!valid) return
        this.$http.post('roles', this.addFromRoles).then(res => {
          if (res.data.meta.status !== 201) {
            return this.$message.error(res.data.meta.msg)
          }
          this.$message.success(res.data.meta.msg)
          this.SetAddRightDialogVisible = false
          this.getRolesList()
          this.$refs.addFromUserRef.resetFields()
          this.addFromRoles.roleDesc = ''
        })
      })
    },
    // 修改角色信息展示
    setUpdateRoles (id) {
      this.$http.get('roles/' + id).then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error(res.data.meta.msg)
        }
        this.updateFromRoles = res.data.data
        this.SetUpdateRightDialogVisible = true
      })
    },
    // 监听关闭修改角色对话框
    updateRolesClosed () {
      this.$refs.updateFromUserRef.resetFields()
    },
    // 修改请求
    SetUpdateRolesData (id) {
      this.$refs.updateFromUserRef.validate(valid => {
        if (!valid) return
        this.$http.put('roles/' + this.updateFromRoles.roleId * 1, this.updateFromRoles).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error(res.data.meta.msg)
          }
          this.$message.success(res.data.meta.msg)
          this.SetUpdateRightDialogVisible = false
          this.getRolesList()
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }

  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
